package com.supreme.nettyapp.generalclient.beatclient.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@ChannelHandler.Sharable
public class BeatClientHandler extends ChannelInboundHandlerAdapter {

    private static final ByteBuf HEARTBEAT_SEQUENCE =
            Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("HEARTBEAT", StandardCharsets.UTF_8));

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        Thread thread = Thread.currentThread();
        long threadId = thread.getId();

        if (evt instanceof IdleStateEvent event) {
            String type = "";
            switch (event.state()) {
                case READER_IDLE:
                    type = "read idle";
                    break;

                case WRITER_IDLE:
                    type = "write idle";
                    ctx.writeAndFlush("ping\n");
                    break;

                case ALL_IDLE:
                    type = "all idle";
                    ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate());
                    break;
            }

            SocketAddress remoteAddress = ctx.channel().remoteAddress();
            System.out.printf("线程ID: %s -> 服务器IP: %s -> 超时类型: %s\n", threadId, remoteAddress, type);
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client Active Date = " + LocalDateTime.now());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client InActive Date = " + LocalDateTime.now());
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String message = (String) msg;
        System.out.println(message);
        if (message.equals("Heartbeat")) {
            ctx.writeAndFlush("has read message from server\n");
        }
    }
}
